package com.qdsgjsfk.vision.ui;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Build;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.qdsgjsfk.vision.R;

import com.qdsgjsfk.vision.eventbus.BlueTooth;
import com.qdsgjsfk.vision.ui.fragment.AxisFragment;
import com.qdsgjsfk.vision.ui.fragment.OtherChooseFragment;
import com.qdsgjsfk.vision.util.Constant;
import com.qdsgjsfk.vision.util.ToastUtil;
import com.rest.business.RestProxy;
import com.rest.response.StudentClassResponse;
import com.rest.response.StudentInfoResponse;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import jz.joyoung.robot.util.LogUtil;

import com.qdsgjsfk.vision.base.BaseActivity;
import com.qdsgjsfk.vision.base.BaseApplication;
import com.qdsgjsfk.vision.eventbus.StartVision;
import com.qdsgjsfk.vision.service.SocketService;
import com.qdsgjsfk.vision.ui.dialog.DistanceDialog;
import com.qdsgjsfk.vision.ui.dialog.VisionModelDialog;
import com.qdsgjsfk.vision.ui.fragment.DiopterFragment;
import com.qdsgjsfk.vision.ui.fragment.VisionFragment;
import com.qdsgjsfk.vision.util.NetUtil;

import java.util.Objects;

import util.PreferencesHelper;
import util.ServiceUtil;

/**
 * 筛查信息界面，包含其他
 *
 * @time 2020/9/25 15:55
 */

public class StudentDetailOtherActivity extends BaseActivity {
    @BindView(R.id.timeline_tablayout)
    TabLayout mTabLayout;
    @BindView(R.id.timeline_viewpager)
    ViewPager mViewPager;

    @BindView(R.id.tv_stu_info)
    TextView tv_stu_info;
    @BindView(R.id.distance)
    TextView distance;
    @BindView(R.id.tv_stu_name)
    TextView tvStuName;
    @BindView(R.id.tv_stu_class)
    TextView tvStuClass;
    @BindView(R.id.btn_back)
    ImageView btnBack;
    @BindView(R.id.icon_switch)
    ImageView iconSwitch;
    @BindView(R.id.title)
    RelativeLayout title;
    private VisionModelDialog mVisionModelDialog;
    private DistanceDialog mDistanceDialog;
    //    long classId;
    String studentId;
    String taskId;
    int tab;

    @Override
    protected void initViews() {
        distance.setVisibility( View.GONE );
        LogUtil.e( "配置其他项" + BaseApplication.isShowOther + "--" + BaseApplication.isShowAxis );
        if (BaseApplication.isShowAxis && BaseApplication.isShowOther) {
            mViewPager.setAdapter( new StudentDetailOtherAdapter( getSupportFragmentManager() ) );
        } else if (BaseApplication.isShowAxis || BaseApplication.isShowOther) {
            mViewPager.setAdapter( new StudentDetailAdapter( getSupportFragmentManager() ) );
        }
        mTabLayout.setupWithViewPager( mViewPager );
        mTabLayout.setTabMode( TabLayout.MODE_FIXED );
        mTabLayout.setTabGravity( TabLayout.GRAVITY_FILL );
        //setIndicatorWidth( mTabLayout, 60 );
        LogUtil.e( "配置tab--" + tab + "" );

        //滑动监听
        mViewPager.addOnPageChangeListener( new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                if (position == 0) {
//                    EventBus.getDefault().postSticky( new BlueTooth( "", 5 ) );
                    iconSwitch.setVisibility( View.VISIBLE );
                } else if (position == 1) {
                    iconSwitch.setVisibility( View.INVISIBLE );
                } else if (position == 2) {
                    iconSwitch.setVisibility( View.INVISIBLE );
                }
            }

            @Override
            public void onPageScrollStateChanged(int state) {
                //1按下时调用，抬起时如果发生了滑动值会变为2（不发生滑动不会有2），滑动结束时变为0
                Log.e( "ScrollStateChanged", state + "" );
            }
        } );

        if (tab == -1) {
            mViewPager.setCurrentItem( BaseApplication.currentTab );
            Objects.requireNonNull( mTabLayout.getTabAt( BaseApplication.currentTab ) ).select();
        } else {
            mViewPager.setCurrentItem( tab );
            Objects.requireNonNull( mTabLayout.getTabAt( tab ) ).select();
        }
//        btnBack.setOnClickListener( new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                //通知视力好屈光页面，返回键
//                EventBus.getDefault().postSticky( new BlueTooth( "", 4 ) );
//                //Toast.makeText( StudentDetailActivity.this, "ddddd", Toast.LENGTH_SHORT ).show();
//            }
//        } );
    }


    public void setmViewPager(int i) {
        mViewPager.setCurrentItem( i );
        Objects.requireNonNull( mTabLayout.getTabAt( i ) ).select();

    }


    @Override
    protected void initData() {
        EventBus.getDefault().register( this );
//        classId = getIntent().getLongExtra("classId", 0);
        studentId = getIntent().getStringExtra( "studentId" );
        taskId = getIntent().getStringExtra( "taskId" );
        tab = getIntent().getIntExtra( "tab", -1 );
//        getStudentById();
        BaseApplication.lastActivity = 2;
        getInfo();
        LogUtil.e( "serviceStuDetail---" + ServiceUtil.isServiceExisted( this, "com.qdsgjsfk.vision.service.SocketService" ) );
        if (!ServiceUtil.isServiceExisted( this, "com.qdsgjsfk.vision.service.SocketService" )) {
            stopService( new Intent( this, SocketService.class ) );
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                startForegroundService( new Intent( this, SocketService.class ) );
            } else {
                startService( new Intent( this, SocketService.class ) );
            }
        }
    }

    /**
     * 获取学生筛查信息（屈光 更新）
     *
     * @time 2020/5/27 13:46
     */
    private void getInfo() {
        RestProxy.getInstance().getStudentInfoQG( studentId + "", taskId, new Observer<StudentInfoResponse>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(StudentInfoResponse studentInfoResponse) {
                tvStuName.setText( studentInfoResponse.data.studentName );
                tvStuClass.setText( studentInfoResponse.data.fullClassName );
            }

            @Override
            public void onError(Throwable e) {
                e.printStackTrace();
                NetUtil.onError( e, StudentDetailOtherActivity.this );

            }

            @Override
            public void onComplete() {

            }
        } );
    }

    @OnClick(R.id.icon_switch)
    void icon_switch() {
        showModelDialog();
    }

    @OnClick(R.id.icon_connect_device)
    void btn_connect_device() {
        startActivity( DeviceTypeActivity.class );
        BaseApplication.studentId = studentId;
        BaseApplication.taskId = taskId;
        finish();
    }


    private void showModelDialog() {
        mVisionModelDialog = VisionModelDialog.newInstance();
        mVisionModelDialog.show( getSupportFragmentManager(), "mVisionModelDialog" );
    }

    private void showDistanceDialog() {
        mDistanceDialog = DistanceDialog.newInstance();
        mDistanceDialog.show( getSupportFragmentManager(), "mDistanceDialog" );
        mDistanceDialog.setmListener( new DistanceDialog.OnItemClickListener() {
            @SuppressLint("SetTextI18n")
            @Override
            public void onConfirm() {
                if (BaseApplication.currentDistance == 3) {
                    distance.setText( "3m" );
                } else {
                    distance.setText( "5m" );
                }
            }

            @Override
            public void onCancel() {

            }
        } );
    }


    @Override
    protected int getLayoutResource() {
        return R.layout.activity_student_detail;
    }


    class StudentDetailAdapter extends FragmentPagerAdapter {
        private static final int PAGE_COUNT = 3;


        StudentDetailAdapter(FragmentManager fm) {
            super( fm );
        }

        @Override
        public Fragment getItem(int position) {
            switch (position) {
                case 0:
                    return VisionFragment.newInstance( studentId, taskId, "2" );
                case 1:
                    return DiopterFragment.newInstance( studentId, taskId, "3" );
                case 2:
                    if (BaseApplication.isShowAxis) {
                        return AxisFragment.newInstance( studentId, taskId );
                    } else if (BaseApplication.isShowOther) {
                        return OtherChooseFragment.newInstance( studentId, taskId );
                    }

                default:
                    return new VisionFragment();
            }
        }

        @Override
        public int getCount() {
            return PAGE_COUNT;
        }

        @Override
        public CharSequence getPageTitle(int position) {
            switch (position) {
                case 0:
                    return "视力";
                case 1:
                    return "屈光";
                case 2:
                    if (BaseApplication.isShowAxis) {
                        return "眼轴";
                    } else if (BaseApplication.isShowOther) {
                        return "其他";
                    }


                default:
                    return "";
            }
        }

    }

    class StudentDetailOtherAdapter extends FragmentPagerAdapter {
        private static final int PAGE_COUNT = 4;


        StudentDetailOtherAdapter(FragmentManager fm) {
            super( fm );
        }

        @Override
        public Fragment getItem(int position) {
            switch (position) {
                case 0:
                    return VisionFragment.newInstance( studentId, taskId, "2" );
                case 1:
                    return DiopterFragment.newInstance( studentId, taskId, "3" );
                case 2:
                    return AxisFragment.newInstance( studentId, taskId );
                case 3:
                    return OtherChooseFragment.newInstance( studentId, taskId );
                default:
                    return new VisionFragment();
            }
        }

        @Override
        public int getCount() {
            return PAGE_COUNT;
        }

        @Override
        public CharSequence getPageTitle(int position) {
            switch (position) {
                case 0:
                    return "视力";
                case 1:
                    return "屈光";
                case 2:
                    return "眼轴";
                case 3:
                    return "其他";
                default:
                    return "";
            }
        }

    }

    @OnClick(R.id.distance)
    void distance() {
        showDistanceDialog();

    }

    private void getStudentById() {
        RestProxy.getInstance().getStudentById( studentId + "", PreferencesHelper.getInstance().getString( this, "token" ), new Observer<StudentClassResponse>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(StudentClassResponse studentClassResponse) {
                tv_stu_info.setText( studentClassResponse.data.remark + "  " + studentClassResponse.data.name );
            }

            @Override
            public void onError(Throwable e) {
                e.printStackTrace();
                NetUtil.onError( e, StudentDetailOtherActivity.this );
            }

            @Override
            public void onComplete() {

            }
        } );
    }


    @Override
    protected void onDestroy() {
        EventBus.getDefault().unregister( this );
        try {
            //这里写可能出现异常的语句
            BaseApplication.currentTab = mTabLayout.getSelectedTabPosition();
        } catch (Exception e) {
            // 捕获异常，如果要捕获Json数据异常，写catch(JSONException e)
            e.printStackTrace();
        }
        super.onDestroy();
    }

    //粘性事件的接收
    @Subscribe(threadMode = ThreadMode.MAIN, sticky = true)
    public void onMessageEvent(StartVision event) {

        Log.e( "StartVision------", event.Start + "" );
        if (event.Start == 1 || event.Start == 2) {
            iconSwitch.setVisibility( View.INVISIBLE );
        } else if (event.Start == 0) {
            iconSwitch.setVisibility( View.VISIBLE );
        } else if (event.Start == 3) {
            iconSwitch.setVisibility( View.VISIBLE );
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(BlueTooth event) {
        LogUtil.e( "onMessageEvent" );
        if (event.type == Constant.CODE_WS_SUCCESS) {
            ToastUtil.showToastCenter( mContext, event.output );
        }
    }


    @Override
    protected void onResume() {
        super.onResume();
    }
//
//    //设置返回键动作（防止按返回键直接退出程序)
//    @Override
//    public boolean onKeyDown(int keyCode, KeyEvent event) {
//        // TODO 自动生成的方法存根
//        if (keyCode == KeyEvent.KEYCODE_BACK) {
//            if (true) {//当webview不是处于第一页面时，返回上一个页面
//
//                return true;
//            } else {//当webview处于第一页面时
//                finish();
//            }
//
//
//        }
//        return super.onKeyDown( keyCode, event );
//    }
}
